/*
 * @Description: 路由转发
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-19 16:00:42
 * @LastEditTime: 2022-07-07 14:54:59
 */
import Koa from 'koa'
import Router from '@koa/router'
import Micro from 'tcp-micro-service'
import microReady from './mid/microReady.js'
import permission from './mid/permission.js'
import microConn from './mid/microConn.js'

interface IRouterCtx extends Koa.ParameterizedContext<any, Router.RouterParamContext<any, {}>, any> {
    micro?: Micro
}

// 创建路由实例
const router = new Router()

// 路由转发
router.all(
    /^\/api(\/\w+([A-Za-z0-9_-]+\w+)?){2,}$/, // 前缀`/api/:service/*`
    microReady(), // 挂载Micro
    permission(), // 权限验证、访问过滤
    microConn(), // 服务连接
    async (ctx: IRouterCtx) => {
        const { path: reqPath, method, header, body, query, host, ip } = ctx.request
        // header需传 'access-token'、'token'

        // console.log("==header.timeout", header.timeout)

        // 获取cookie
        // console.log("ctx.cookies.get('mycookie')", ctx.cookies.get('mycookie'))

        // 设置cookie
        // ctx.cookies.set('mycookie', Date.now() + '')

        // 请求
        const res = await ctx.micro.request({
            service: reqPath.match(/^\/api\/(?<service>[A-Za-z0-9_-]+)/)?.groups?.service,
            path: reqPath.match(/^\/api\/[A-Za-z0-9_-]+(?<path>.+)$/)?.groups?.path,
            data: {
                method,
                header,
                query,
                body,
                host,
                ip,
            },
        })

        if (res.ok === -1) {
            ctx.status = res.status
        }

        ctx.body = res
    })

export default router